from odoo import api, fields, models
from odoo.exceptions import UserError
from werkzeug.utils import redirect
from oauth2client.client import OAuth2WebServerFlow
from ...functions.marketing_adjustment_func import MarketingAdjustmentFunc

TEMPLATE_STATE = [('draft', '草稿'), ('await_enable', '待生效'), ('enable', '激活'), ('expired', '弃用')]
FULFILLMENT_TYPE = [('dropoff', '网点收件'), ('pickup', '上门取件'), ('collect', '网点取件'), ('delivery', '送货上门')]
ADJUSTMENT_CATEGORY = [('all_mail_route', '所有邮路'), ('single_mail_route', '单一邮路'), ('single_value_add', '单一增值'), ('all_value_add', '所有增值(二类)')]
# 增值服务类别
VALUE_CATEGORY = [('one', '一类'), ('two', '二类')]


class RpMarketingAdjustPriceTemplate(models.Model):
    _name = 'rp.marketing.adjust.price.template'
    _description = '营销调价模板'
    _inherit = ['mail.thread', 'mail.activity.mixin']
    _rec_name = 'code'

    name = fields.Char(string='名称', required=True, copy=False, index=True, tracking=True)
    code = fields.Char(string='编码', default='RP_MAPT/***', readonly=True, required=True, copy=False, index=True, tracking=True)
    special_customer_tag = fields.Boolean(string='特殊客户标志', default=False, copy=False, tracking=True)

    rp_customer_id = fields.Many2one(string='特殊客户', comodel_name='rp.customer', default=False, index=True, tracking=True)
    customer_level_tag = fields.Boolean(string='客户等级', default=True, copy=False)
    customer_category_tag = fields.Boolean(string='客户分类', default=True, copy=False)
    customer_level_ids = fields.Many2many(string='客户等级', comodel_name='rp.customer.level', column1='adjust_price_template_id', column2='customer_level_id',
                                          relation='price_template_customer_level_rel', copy=False)
    customer_category_ids = fields.Many2many(string='客户分类', comodel_name='rp.customer.category', column1='adjust_price_template_id', column2='customer_category_id',
                                             relation='price_template_customer_category_rel', copy=False)

    rp_price_adjust_rule_id = fields.Many2one(string='调价规则', comodel_name='rp.price.adjust.rule', required=True, copy=False)
    adjust_for = fields.Selection(string='调价对象', selection=ADJUSTMENT_CATEGORY, default=ADJUSTMENT_CATEGORY[0][0], required=True, copy=False)
    rp_shipper_id = fields.Many2one(string='托运商', comodel_name='rp.shipper', copy=False, required=True)
    value_added_selection = fields.Selection(string='增值服务', selection=VALUE_CATEGORY, default=VALUE_CATEGORY[0][0], copy=False)
    rp_shipper_value_added_id = fields.Many2one(string='增值服务', comodel_name='rp.shipper.sale.template.value.added.line')
    rp_shipper_mail_route_id = fields.Many2one(string='邮路', comodel_name='rp.shipper.sale.template.mail.route.line', domain=[('shipper_id', '=', rp_shipper_id), ('active_flag', '=', True)])

    validate_time = fields.Date(string='生效时间', copy=False, required=True)
    expired_time = fields.Date(string='截止时间', copy=False, required=True)
    validity_display = fields.Char(string='有效期', compute='depends_on_data_time', copy=False)
    data_create = fields.Datetime(string='创建时间', default=fields.Datetime.now, copy=False)
    template_state = fields.Selection(string='状态', selection=TEMPLATE_STATE, default=TEMPLATE_STATE[0][0], copy=False)
    validate_flag = fields.Boolean(string='有效', compute='depends_on_template_flag')
    remark = fields.Text(string='备注', copy=False)

    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            vals['code'] = self.env['ir.sequence'].sudo().next_by_code('rp.marketing.adjust.price.template') or '/'
            # 校验历史记录
            MarketingAdjustmentFunc(self.env).validate_history_record(vals.get('customer_level_ids')[0][2], vals.get('customer_category_ids')[0][2], vals.get('special_customer_tag'), vals.get('rp_customer_id'),
                                                                    vals.get('code'), vals.get('adjust_for'), vals.get('rp_shipper_id'), vals.get('rp_shipper_value_added_id'), vals.get('rp_shipper_mail_route_id'))
        results = super(RpMarketingAdjustPriceTemplate, self).create(vals_list)
        for result in results:
            if result.validate_time > fields.date.today():
                result.write({'template_state': 'await_enable'})
            else:
                result.write({'template_state': 'enable'})
        return results

    def write(self, vals):
        # self.code != 'RP_MAPT/***'    失效时不应走历史校验逻辑,点击创建时，如果触发write方法也不应该走历史校验逻辑
        if len(vals) != 0 and any([vals.get('validate_flag') is False, vals.get('template_state') == 'expired']) and self.code != 'RP_MAPT/***':
            # 只有失效模板或创建模板时不执行历史校验，直接返回
            return super(RpMarketingAdjustPriceTemplate, self).write(vals)

        def custom_read_logic(record, field_name):
            if field_name == 'rp_customer_id':
                return record.rp_customer_id.id
            elif field_name == 'rp_shipper_id':
                return record.rp_shipper_id.id
            elif field_name == 'rp_shipper_value_added_id':
                return record.rp_shipper_value_added_id.id
            elif field_name == 'rp_shipper_mail_route_id':
                return record.rp_shipper_mail_route_id.id
            else:
                getattr(record, field_name)

        # 新建模板或者本身已经是禁用状态的调价模板，因为刷新而触发depends->到write也不应该触发历史校验
        if len(vals) != 0 and self.code != 'RP_MAPT/***' and self.template_state != 'expired':
            # 将对象转化为字典，自定义读取规则
            record = self.read(load='custom_read_logic')[0]
            record.update(vals)
            # 编辑信息时校验历史数据
            MarketingAdjustmentFunc(self.env).validate_history_record(record.get('customer_level_ids'), record.get('customer_category_ids'), record.get('special_customer_tag'), record.get('rp_customer_id'),
                                                                      record.get('code'), record.get('adjust_for'), record.get('rp_shipper_id'), record.get('rp_shipper_value_added_id'), record.get('rp_shipper_mail_route_id'))
        return super(RpMarketingAdjustPriceTemplate, self).write(vals)

    @api.constrains('validate_time', 'expired_time')
    def _constrains_start_end_date(self):
        if self.validate_time and self.expired_time:
            if self.validate_time >= self.expired_time:
                raise UserError('结束时间应该在开始时间之后！')
            if self.expired_time <= fields.Date.today():
                raise UserError('不可以创建无效的优惠券模板！')

    @api.onchange('special_customer_tag')
    def _on_change_for_special_customer(self):
        if self.special_customer_tag:
            self.write({'customer_level_ids': False, 'customer_category_ids': False, 'customer_category_tag': False, 'customer_level_tag': False})
        else:
            self.write({'rp_customer_id': False})

    @api.onchange('adjust_for')
    def _onchange_price_adjust_line(self):
        if self.adjust_for == ADJUSTMENT_CATEGORY[0][0]:
            self.update({'rp_shipper_mail_route_id': False,
                         'rp_shipper_value_added_id': False,
                         'rp_price_adjust_rule_id': False})
        if self.adjust_for == ADJUSTMENT_CATEGORY[1][0]:
            self.update({'rp_shipper_value_added_id': False,
                         'rp_price_adjust_rule_id': False})
        if self.adjust_for == ADJUSTMENT_CATEGORY[2][0]:
            self.update({'rp_shipper_mail_route_id': False,
                         'rp_price_adjust_rule_id': False})
        if self.adjust_for == ADJUSTMENT_CATEGORY[3][0]:
            self.update({'rp_shipper_mail_route_id': False,
                         'rp_shipper_value_added_id': False,
                         'rp_price_adjust_rule_id': False})

    @api.onchange('customer_level_tag', 'customer_category_tag')
    def _onchange_category_level_tag(self):
        if self.special_customer_tag is False:
            # 等级和分类取消勾选会默认为全部
            if not self.customer_level_tag:
                customer_level_ids = self.env['rp.customer.level'].search([])
                self.update({'customer_level_ids': [(6, 0, customer_level_ids.ids)]})
            if not self.customer_category_tag:
                customer_category_ids = self.env['rp.customer.category'].search([])
                self.update({'customer_category_ids': [(6, 0, customer_category_ids.ids)]})
            # 如果勾选会将对应字段的值清除
            if self.customer_level_tag:
                self.update({'customer_level_ids': False})
            if self.customer_category_tag:
                self.update({'customer_category_ids': False})

    @api.depends('template_state')
    def depends_on_template_flag(self):
        for record in self:
            if record.template_state == 'draft':
                record.write({'validate_flag': False})
            if record.template_state == 'enable':
                record.write({'validate_flag': True})
            if record.template_state == 'expired':
                record.write({'validate_flag': False})
            if record.template_state == 'await_enable':
                record.write({'validate_flag': False})

    @api.depends('validate_time', 'expired_time')
    def depends_on_data_time(self):
        for record in self:
            if record.validate_time and record.expired_time:
                time_gap = (record.expired_time - record.validate_time).days
                if time_gap < 0:
                    raise UserError('请填写有效的时间期限！')
                else:
                    record.write({'validity_display': f'{time_gap}天'})
            else:
                record.write({'validity_display': ''})

    def turn_enable(self):
        """
        启用调价模板
        """
        # 判断模板是否过期【已过期的模板不可启用】
        if self.expired_time < fields.Date.today():
            raise UserError('该调价模板已过期，禁止启用！')
        # 校验历史记录是否冲突
        MarketingAdjustmentFunc(self.env).validate_history_record(self.customer_level_ids.ids, self.customer_category_ids.ids, self.special_customer_tag, self.rp_customer_id.id,
                                                                  self.code, self.adjust_for, self.rp_shipper_id.id, self.rp_shipper_value_added_id.id, self.rp_shipper_mail_route_id.id)
        self.write({'template_state': 'enable'})

    def turn_expired(self):
        """
        禁用调价模板
        """
        self.ensure_one()
        self.write({'template_state': 'expired'})


